﻿// 文档32: ThemeService.cs
using System.Windows;
using System.Windows.Media;
using System.Collections.Generic;

namespace StudentInfoSystem.UI.Services;
public static class ThemeService
{
    // 预加载所有主题资源
    private static  Dictionary<string, ResourceDictionary> _preloadedThemes;

    private static ResourceDictionary CreateThemeResource(string themeName)
    {
        return new ResourceDictionary
        {
            Source = new Uri($"/Resources/Themes/{themeName}.xaml", UriKind.Relative)
        };
    }
    public static void PreloadResources()
    {
        _preloadedThemes = new()
        {
            ["Dark"] = CreateThemeResource("DarkTheme"),
            ["Light"] = CreateThemeResource("LightTheme")
        };
    }

    public static void ApplyTheme(bool isDarkTheme)
    {
        var themeKey = isDarkTheme ? "Dark" : "Light";
        var newTheme = _preloadedThemes[themeKey];

        // 动态更新资源而不是替换整个字典
        UpdateDynamicResources(newTheme);
    }

    private static void UpdateDynamicResources(ResourceDictionary newTheme)
    {
        var app = Application.Current;

        // 1. 更新全局资源
        foreach (var key in newTheme.Keys)
        {
            if (app.Resources.Contains(key))
            {
                app.Resources[key] = newTheme[key];
            }
            else
            {
                app.Resources.Add(key, newTheme[key]);
            }
        }

        // 2. 特别处理需要动态刷新的依赖属性
        RefreshVisualTree(app.MainWindow);
    }

    private static void RefreshVisualTree(DependencyObject obj)
    {
        // 递归刷新整个视觉树
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
        {
            var child = VisualTreeHelper.GetChild(obj, i);
            if (child is FrameworkElement element)
            {
                // 强制刷新动态资源绑定
                element.InvalidateVisual();
                element.InvalidateArrange();
                element.InvalidateMeasure();
            }
            RefreshVisualTree(child);
        }
    }
}